//
//  UserViewController.m
//  ThePrivateKitchen
//
//  Created by lirui on 16/1/20.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "UserViewController.h"
#import "Frame.h"
#import "LoginViewController.h"
#import "AppDelegate.h"
#import "SaveViewController.h"
#import "BackViewController.h"
#import "SetViewController.h"
#import "WeViewController.h"
#import "UMSocial.h"
@interface UserViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)UIView *hView;
@property(nonatomic,assign)BOOL isClick;
@property(nonatomic, retain)UIView *backView;
@property(nonatomic, retain)UIButton *left;

@end

@implementation UserViewController
{
    UIImageView *head;
    UILabel *label;
    UIButton *state;
}


- (void)dealloc
{
   
    [_tableView release];
   
    [super dealloc];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //每次视图将要出现时 判断左上角的按钮状态
   BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"];
    
    if (isLogin) {
       
        [_left setTitle:@"退出" forState:UIControlStateNormal];
        [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToSina  completion:^(UMSocialResponseEntity *response){
            
            NSLog(@"SnsInformation is %@",response.data);
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary:response.data];
            [head sd_setImageWithURL:[dic objectForKey:@"profile_image_url"] placeholderImage:[UIImage imageNamed:@"userHeadImage@2x"]];
            label.text = [dic objectForKey:@"screen_name"];
        }];

        
    }else
    {
        
        [_left setTitle:@"登录" forState:UIControlStateNormal];

    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [ UIColor whiteColor];
     //标题
    self.navigationItem.title = @"我的";
   
    //重写左按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"shezhi"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(shezhiAction:)];
   self.left = [ UIButton buttonWithType: UIButtonTypeSystem];
    [_left setTitle:@"登录" forState:UIControlStateNormal];
    [_left setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
   _left.frame = CGRectMake(WIDTH *100, 0, 40*WIDTH, 40*HEIGHT);
    [_left addTarget:self action:@selector(dian:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc]initWithCustomView:_left];
     self.navigationItem.leftBarButtonItem = bar;
    
    [self creatView];
    [self headView];
 
    self.tableView.tableHeaderView =self.hView;
    
    //夜间模式
    //UIApplication delegate
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    self.backView  = [[ UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH *375, HEIGHT *667)];
    self.backView.backgroundColor = [UIColor blackColor];
    self.backView.alpha = 0.7;
    self.backView.userInteractionEnabled = NO;
    [delegate.window addSubview:_backView];
    _backView.hidden = YES;
    [_backView release];

   
    
}
-(void)shezhiAction:(UIBarButtonItem *)shezhi
{
    SetViewController *sett = [[ SetViewController alloc] init];
    [self.navigationController pushViewController:sett animated:YES];
    
    
}
//头部区域
-(void)headView
{
    self.hView = [[ UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH *375 , HEIGHT *667- 400*HEIGHT)];
    //_hView.backgroundColor = [ UIColor redColor];
    UIImageView *img = [[ UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH *375, HEIGHT  *667- 400*HEIGHT)];
    img.backgroundColor = [ UIColor redColor];
    img.image = [ UIImage imageNamed:@"login.jpg"];
    [_hView addSubview:img];
   label = [[ UILabel alloc] initWithFrame:CGRectMake(0, img.frame.size.height - 80*WIDTH, WIDTH *375, HEIGHT * 80)];
    label.backgroundColor = [UIColor blackColor];
    label.text = @"每个吃货都是有头有脸的,快去登录吧";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [ UIColor whiteColor];
    label.alpha = 0.6;
    [img addSubview:label];
    //设置头像imageView
    head = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * 20, img.frame.size.height - HEIGHT*105,WIDTH * 50,HEIGHT * 50)];
    head.image = [ UIImage imageNamed:@"userHeadImage@2x"];
    head.layer.cornerRadius = 50 / 2;
    head.layer .masksToBounds = YES;
    [_hView addSubview:head];
    [label release];
    [_hView release];
    [img release];
    [head release];
    
    
}
#pragma mark -创建tableview
-(void)creatView
{ self.tableView =  [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH *375, HEIGHT *667) style:UITableViewStylePlain];
   // _tableView.backgroundColor = [ UIColor whiteColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 20, 0);
    [_tableView release];
    
}
#pragma mark -必须实现的方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section ==1) {
        return 1;
    }else if (section ==2) {
        return 1;
    }else if (section == 3){
        return 1;
    }
else
    return 0;
    
}
#pragma mark -cell设置
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    if (indexPath.section ==0) {
        if (indexPath.row == 0) {
            cell.textLabel.text =@"我的收藏";
        }
    }
    if (indexPath.section ==1) {
        if (indexPath.row == 0) {
            cell.textLabel.text =@"清除缓存";
        }
    }
    if (indexPath.section ==2) {
        if (indexPath.row == 0) {
            cell.textLabel.text =@"夜间模式";
            /**夜间模式的开关*/
            UISwitch *switchcontroll1 = [[ UISwitch  alloc] init];
            [switchcontroll1 addTarget:self action:@selector(switchAction1:) forControlEvents:UIControlEventValueChanged];
            cell.accessoryView = switchcontroll1;
            [switchcontroll1 release];
        }
    }
    if (indexPath.section ==3) {
        if (indexPath.row == 0) {
            cell.textLabel.text =@"反馈意见";
        }
}
      return cell;


}

//夜间模式开关控制方法
-(void)switchAction1:(UISwitch *)s
{//开启时
    if (s.on) {
        self.backView .hidden = NO;
    }else
    {
        self.backView.hidden = YES;
    }
    
}

#pragma mark -行高设置
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
#pragma mark -头部高度设置
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
    
}
#pragma mark -三方登录按钮
-(void)dian:(UIBarButtonItem *)d
{  

   BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"];
    if (isLogin) {
        
         [_left setTitle:@"登录" forState:UIControlStateNormal];
            [[UMSocialDataService defaultDataService] requestUnOauthWithType:UMShareToSina  completion:^(UMSocialResponseEntity *response){
                NSLog(@"response is %@",response);
                 head.image = [ UIImage imageNamed:@"userHeadImage@2x"];
               label.text = @"每个吃货都是有头有脸的,快去登录下吧";
                                      }];
        
   
         [[NSUserDefaults standardUserDefaults] setBool:false forKey:@"isLogin"];
        
        
    }

        
        
   
    
    else
    {
       
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
        
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
            
            //          获取微博用户名、uid、token等
            
            if (response.responseCode == UMSResponseCodeSuccess) {
                
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
                UIAlertController *c = [UIAlertController alertControllerWithTitle:@"提示" message:@"新浪微博登录成功" preferredStyle:UIAlertControllerStyleAlert];
                
                [self presentViewController:c animated:YES completion:^{
                }];
                
                [self performSelector:@selector(diss) withObject:self afterDelay:2];
                

                NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
                [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToSina  completion:^(UMSocialResponseEntity *response){
                    
                    NSLog(@"SnsInformation is %@",response.data);
                    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:response.data];
                    [head sd_setImageWithURL:[dic objectForKey:@"profile_image_url"] placeholderImage:[UIImage imageNamed:@"userHeadImage@2x"]];
                    label.text = [dic objectForKey:@"screen_name"];
                                   }];
                [_left setTitle:@"退出" forState:UIControlStateNormal];
                NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                [userDefault setBool:true forKey:@"isLogin"];
                
            } else {
                NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                [userDefault setBool:false forKey:@"isLogin"];
            }
        });
    }
    
    
}
-(void)diss
{
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*我的收藏*/
    if (indexPath.row == 0 && indexPath.section == 0) {
        
        SaveViewController *save = [[ SaveViewController alloc] init];
        [self.navigationController pushViewController:save  animated:YES];
   
    }
/**意见反馈*/
if (indexPath.row == 0 && indexPath.section == 3) {
            BackViewController *back = [[ BackViewController alloc] init];
            [self.navigationController pushViewController:back animated:YES];
          
        }
    /**我的缓存*/
    if(indexPath.row == 0 && indexPath.section == 1)
    {
        UIAlertController *cleanAlert =[UIAlertController alertControllerWithTitle:@"清除缓存" message:@"" preferredStyle:UIAlertControllerStyleAlert ];
        //获取缓存大小路径
        NSString *cashPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        //计算文件夹的大小
        CGFloat fileSize = [self folderSizeAtPath:cashPath];
        //计算图片的大小
        CGFloat imageSize = [[SDImageCache sharedImageCache] getSize];
        dispatch_async(dispatch_get_main_queue(), ^{
            //总共的缓存大小
            CGFloat m = fileSize + imageSize/(1024.0*1024.0);
            cleanAlert.message  = [NSString stringWithFormat:@"%.2fMB",m];
            [self.tableView reloadData];
            
        });
    //取消按钮
        UIAlertAction *cancell = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        //确定按钮
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //文件夹清缓存
             [self clean:cashPath];
            //sdimage 清缓存
            [[SDImageCache sharedImageCache] cleanDisk];
        }];
        
        [cleanAlert addAction:cancell];
        [cleanAlert addAction:ok];
        //弹窗出现
        [self presentViewController:cleanAlert animated:YES completion:nil];
    }
        
}
//清除方法
- (void)clean:(NSString *)path{
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
    
    for (NSString *p in files) {
        
        NSError *error;
        
        NSString *Path = [path stringByAppendingPathComponent:p];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
            
            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
            
        }
    }
}
//文件夹计算大小方法 遍历文件夹获得文件夹的大小  返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath])
        return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString* fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
    }
    
    return folderSize/(1024.0*1024.0);
    
}

- (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
        
    }
    
    return 0;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
